package com.imc.core.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;

@Component
public class UploadUtiles {
    @Value("${img.location}")
    private String location;

    @Value("${img.accessPath}")
    private String accessPath;

    //绝对路径
    public String getCurrentAddress(String imgUrl){
        return accessPath+imgUrl;
    }

    //相对路径
    public String getLocationAddress(String imgUrl){
        return location + imgUrl;
    }

    /**
    *QY 2018/10/20 23:38
    *方法描述：上传图片，获取图片路径
    **/
    public String getUpImg(String savePath, MultipartFile file) {
        String relFn = null;
        try {
            if (null != file) {
                String filename = URLEncoder.encode(file.getOriginalFilename(), "utf-8");
                File filepath = new File(savePath, filename);
                //判断路径是否存在，如果不存在就创建一个
                if (!filepath.getParentFile().exists()) {
                    filepath.getParentFile().mkdirs();
                }
                InputStream inputStream = file.getInputStream();
                FileOutputStream fileOutputStream = null;
                String fnName = makeFileName(filename);
                relFn = fnName;
                byte[] data = new byte[1024];
                int len = 0;
                fileOutputStream = new FileOutputStream(savePath + fnName);
                while ((len = inputStream.read(data)) != -1) {
                    fileOutputStream.write(data, 0, len);
                }
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return relFn;
    }

    /**
    *QY 2018/10/21 23:40
    *方法描述：创建新的文件
    **/
    private static String makeFileName(String filename) {
        //为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
        String extname = filename.substring(filename.lastIndexOf("."), filename.length());
        return UUID.randomUUID().toString() + extname;
    }
}
